package com.leetcode.sorts.arrays.matrix;

import java.util.Arrays;

/**
 * @Author: WuPeng
 * @Date: 2021/5/22 2:13 下午
 *
 * 059: 螺旋矩阵
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 *
 */
public class HelixArray_059 {

    public static int[][] solution(int n){

        int[][] res = new int[n][n];

        int x = 0, y=0;
        int offset = 1;
        int count = 1;
        int loop=n/2;

        while(loop > 0){
            int i=x;
            int j=y;

            //上：左到右
            for (; j < y+n-offset; ++j){
                res[x][j] = count++;
            }
            //右：上到下
            for (; i < x+n-offset; ++i){
                res[i][j] = count++;
            }
            //下：右到左
            for (; j > y; j--){
                res[i][j] = count++;
            }
            //左：下到上
            for (; i > x; i--){
                res[i][j] = count++;
            }
            loop--;
            x++;
            y++;
            offset += 2;
        }

        if (n%2 == 1){
            res[n/2][n/2] = count;
        }

        return res;
    }

    public static void main(String[] args) {
        int count = 4;
        int[][] res = solution(count);
        for (int i = 0; i < count; i++) {
            System.out.println(Arrays.toString(res[i]));
        }
    }

}
